#!/bin/bash

link=$1
name=$2
regex=$'(?:boards.4chan.org|archiveofsins.com)\/(.*)\/thread\/(.*)|\\?board\\=(.*)\\&num\\=(.*)'


if [ ! -z "$name" ]; then
	echo "Starting ..."
else
	echo "No filename inputed"
fi

if [[ $link =~ $regex ]]; then
    if [[ ! -z "${BASH_REMATCH[1]}" ]] && [[ ! -z "${BASH_REMATCH[2]}" ]]; then
    	board="${BASH_REMATCH[1]}"
        thread="${BASH_REMATCH[2]}"
    elif [[ ! -z "${BASH_REMATCH[3]}" ]] && [[ ! -z "${BASH_REMATCH[4]}" ]]; then
    	board="${BASH_REMATCH[3]}"
        thread="${BASH_REMATCH[4]}" 
    fi
else
	echo "$link INVALID LINK" >&2
    exit 1
fi

read -p "Download Thread? (y/n) : " downloadThread
if [[ $downloadThread == 'y' ]] || [[ -z "$downloadThread" ]]; then
	./4cget $link
fi


read -p "Begin ffmpeg parse? (y/n) : " ffmpegParse
if [[ $ffmpegParse == 'y' ]] || [[ -z "$ffmpegParse" ]]; then
    if [[ -f "$name.mp4" ]]; then
        read -p "File '$name.mp4' already exists. Do you want to delete it? (y/n) : " fileDelete
        if [[ $fileDelete == 'y' ]] || [[ -z "$fileDelete" ]]; then
            rm "$name.mp4"
            echo "File $name.mp4 was deleted"
        fi
    fi

    folderSize=$(du -hsb ./$board/$thread/ | awk '{print $1}')


    cat ./$board/$thread/*.jpg | pv -p -t -e -s $folderSize | ffmpeg.exe -f image2pipe \
        -hide_banner \
        -loglevel quiet \
        -framerate 1/3 \
        -i - \
        -c:v libx265 \
        -r 24 \
        -s 3840x2160 \
        -vf "scale=3840:2160:force_original_aspect_ratio=decrease:eval=frame,pad=3840:2160:-1:-1:eval=frame" \
        -preset medium \
        -movflags +faststart \
        -pix_fmt yuv420p \
        $name.mp4 \
        > /dev/null 2>&1
fi

echo "End"
